<template>
    <div class="outer">
        <div class="left">
            <div class="headerSelect">
                <el-row :gutter="12">
                    <!-- 选择校区、时间栏 -->
                    <el-col :span="6">
                        <!-- 选择学期 -->
                        <el-select v-model="sessionSelected" @Change="sessionSelectChange" style="width:200px">
                            <el-option v-for="(item) in sessions" :key="item.sessionId" :value="item"
                                :label=sessionSelected.sessionName>
                                <span>
                                    {{ selectSessionLabel(item) }}
                                    <el-icon v-if="item.cur == true">
                                        <StarFilled />
                                    </el-icon>
                                </span>
                            </el-option>
                        </el-select>
                    </el-col>

                    <!-- 校区 -->
                    <el-col :span="4">
                        <el-radio-group v-model="campusSelected" class="capmus-radio">
                            <el-radio v-for="(v, index) in campus" :value="v" :key=index>{{ v }}</el-radio>
                        </el-radio-group>
                    </el-col>
                    <!-- 今天/本周 -->
                    <el-col :span="4" justify="start">
                        <el-radio-group v-model="dayOrWeek" @change="dayAndWeekChange(dayOrWeek)">
                            <el-radio-button :value="2">周视图</el-radio-button>
                            <el-radio-button :value="1">日视图</el-radio-button>
                        </el-radio-group>
                    </el-col>
                    <el-col :span="6">
                        <!-- 周视图，选择第几周  -->
                        <div v-if="dayOrWeek == 2">
                            <el-date-picker v-model="dayViewSelected" type="week" @change="weekViewChange"
                                :clearable="false" placeholder="当前周" :disabled-date="checkValidDate"
                                :shortcuts="dateAndWeekShortcuts" style="width:240px" />


                        </div>
                        <!-- 日视图，选择具体哪一天 -->
                        <div v-if="dayOrWeek == 1">
                            <el-date-picker v-model="dayViewSelected" type="date" :editable="false" :clearable="false"
                                :disabled-date="checkValidDate" :shortcuts="dateAndWeekShortcuts"
                                @change="dayViewChange" style="width:240px" />

                        </div>
                    </el-col>
                    <el-col :span=4>
                        <el-tooltip :content="(dayOrWeek==1)?'昨天':'上周'" placement="bottom">
                            <el-button type="success" round
                                @click="dayViewSelected = dayjs(dayViewSelected).subtract(1, (dayOrWeek==1)?'day':'week').toDate()"
                                :icon="ArrowLeft"></el-button>
                        </el-tooltip>
                        <el-tooltip :content="(dayOrWeek == 1) ? '今天' : '本周'" placement="bottom">
                            <el-button type="success" round @click="dayViewSelected = new Date()"
                                :icon="Star"></el-button>
                        </el-tooltip>
                        <el-tooltip :content="(dayOrWeek == 1) ? '明天' : '下周'" placement="bottom">
                            <el-button type="success" round
                                @click="dayViewSelected = dayjs(dayViewSelected).add(1, (dayOrWeek == 1) ? 'day' : 'week').toDate()"
                                :icon="ArrowRight"></el-button>
                        </el-tooltip>
                    </el-col>
                </el-row>
            </div>

            <div v-loading="loading" class="mainbox" style="padding:10px,15px;justify-content: center;">
                <!--  week -->
                <div v-if="dayOrWeek == 2">
                    <el-table :data="courseTableData" class="coure_table" :span-method="courseTbaleSpan" border stripe
                        table-layout="auto" height="75vh">
                        <el-table-column :v-if="getCurrentWeeks.length!==0" prop="content" label="节次" align="center"
                            min-width="10px" />
                        <el-table-column :v-if="getCurrentWeeks.length!== 0" prop="labName" label="实验室" align="center"
                            min-width="10px" />
                        <el-table-column v-for="(item, index) in getCurrentWeeks" :key="index" min-width="5px"
                            :label="courseTableHeader(item)" align="center">
                            <template #default="scope">
                                <div v-for="(val, index) in scope.row[item]" :key="index">
                                    <span>
                                        <span>{{ val.course.courseName }}</span>
                                        <el-divider direction="vertical" />
                                        <span style="font-size:xx-small;font-weight:bold">{{ val.user.userName }}</span>
                                    </span>
                                </div>
                            </template>
                        </el-table-column>

                    </el-table>
                </div>
                <!-- day -->
                <div v-if="dayOrWeek == 1">
                    <el-table :data="courseTableData" class="coure_table" :span-method="courseTbaleSpan" border stripe
                        style="width:100%" table-layout="auto" height="75vh">
                        <el-table-column prop="content" label="节次" align="center" />
                        <el-table-column prop="data.user.userNumber" label="工号" align="center" />
                        <el-table-column prop="data.user.userName" label="老师" align="center" />
                        <el-table-column prop="data.course.courseName" label="课程名" align="center" />
                        <el-table-column prop="data.lab.labName" label="实验室" align="center" />
                        <el-table-column prop="data.lab.location" label="位置" align="center" />
                        <el-table-column prop="data.course.studentNumber" label="学生数" align="center" />
                        <el-table-column prop="data.course.remark" label="备注" align="center" />
                    </el-table>
                </div>
            </div>

        </div>
        <div class="msg">
            <el-timeline>
                <el-timeline-item v-for="(activity, index) in msg" :key="index" :icon="activity.icon"
                    :type="activity.type" :color="activity.color" :size="activity.size" :hollow="activity.hollow"
                    :timestamp="activity.timestamp" center>
                    <el-card> {{ activity.content }} </el-card>
                </el-timeline-item>
            </el-timeline>
        </div>
    </div>
</template>

<script setup>
import { labsApi } from '@/api/labs'
import { sessionApi } from '@/api/session'
import { courseApi } from '@/api/course'
import { ref,  computed, onUpdated, watchEffect, nextTick } from "vue";

// dayjs 库
import { dayjs } from 'element-plus'
import {ArrowRight,ArrowLeft,Star} from '@element-plus/icons-vue'
import weekday from 'dayjs/plugin/weekday'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import duration from 'dayjs/plugin/duration'
import isBetween from 'dayjs/plugin/isBetween'
import "dayjs/locale/zh-cn";

dayjs.extend(weekday)
dayjs.extend(weekOfYear)
dayjs.extend(duration)
dayjs.extend(isBetween)
dayjs.locale('zh-cn')
// 课程集
const courses = ref(null)
// 实验室位置
const campus = ref(null)
const labs = ref(null)

const sessionSelected = ref(null)
// 学期
const sessions = ref(null)
const isUpdateTable = ref(true)
// const isDayTableViewsUpdateTable = ref(true)
const loading = ref(true)
const tableDisplay = ref(new Set())
// 异步 api
// vue
// icon
import { StarFilled, MoreFilled } from '@element-plus/icons-vue'
// 与ui绑定的值
// 学期选择select



const courseTableData = ref([]);


// 校区位置 radio select
const campusSelected = ref(null)
// day or week 视图选择
const dayOrWeek = ref(1)
// 周视图选择的周次,初始化为当前空
// 日视图选择的日期， 日视图初始化为当前日期
const dayViewSelected = ref(new Date())


const dateAndWeekShortcuts = [
    {
        text: '今日',
        value: new dayjs(),
    },
    {
        text: '开学',
        value: () => {
            const date = new Date(sessionSelected.value.startTime)
            // date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date;
        },

    },
    {
        text: '期末',
        value: () => {
            const date = new Date(sessionSelected.value.endTime)
            // date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date;
        },
    },
]
let curWeeks = computed(() => {
    let startOfWeek = dayjs(dayViewSelected.value).startOf('week');
    let endOfWeek = dayjs(dayViewSelected.value).endOf('week');
    let dates = [];
    while (startOfWeek.isBefore(endOfWeek, 'day')) {
        dates.push(startOfWeek.format('YYYY-MM-DD'));
        startOfWeek = startOfWeek.add(1, 'day');
        // constole.log(startOfWeek)
    }
    // console.log(dates)
    // console.log(dayViewSelected.value,dates)
    return dates;
})

// 选择周后，周选择器中显示的内容
function weekViewChange(value) {
    // console.log('current,', dayViewSelected.value,$event)
    // 垃圾element-plus,回显内容竟然不能定制，逼人太甚
    console.log(value)
    if (value == null) {
        dayViewSelected.value = new Date()
    }

}
function dayViewChange(value) {
    if (value == null)
        dayViewSelected.value = new Date()


}


const getCurrentWeeks = computed(()=> {
    let startOfWeek = dayjs(dayViewSelected.value).startOf('week');
    let endOfWeek = dayjs(dayViewSelected.value).endOf('week');
    let dates = [];
    while (startOfWeek.isSameOrBefore(endOfWeek, 'day')) {
        let cur = startOfWeek.format('YYYY-MM-DD')
        if (tableDisplay.value.has(cur)) {
            dates.push(cur);
        }
        startOfWeek = startOfWeek.add(1, 'day');
        // constole.log(startOfWeek)
    }
    // console.log(dates)
    // console.log(dayViewSelected.value,dates)
    return dates;
})
function courseTableHeader(item) {
    // return item
    return dayjs(item).format('YYYY-MM-DD dd')
}
// function courseTableShow(item) {
//     console.log(item, tableDisplay.value.has(item))
//     return tableDisplay.value.has(item)
// }

// 学期下拉菜单的label内容
function selectSessionLabel(item) {
    // console.log(item)
    return `${item.sessionName} (${dayjs(item.startTime).format('YY-MM-DD')} 至 ${dayjs(item.endTime).format('YY-MM-DD')})`
}

function checkValidDate(d) {
    // 日期验证，不让不让选择非当前学期的日期
    // console.log(typeof(d))
    // new dayjs(sessionSelected.startTime)
    // console.log('@@@',d)
    // return false;
    if(sessionSelected.value!=null)
        return !dayjs(d).isBetween(sessionSelected.value.startTime, sessionSelected.value.endTime,'day','[]')
    return false

}
function sessionSelectChange(data, data2) {
    // console.log(data,sessionSelected.cur)
    // 只有切到当前学期，再更新时间
    // 只要切换到当前学期，便会初始化时间
    if (sessionSelected.value.cur == true) {
        dayViewSelected.data = new Date()
        
    }


}

// function inpurtPrint() {
//     const startWeek = new dayjs(sessionSelected.value.startTime)
//     const cur = new dayjs(dayViewSelected.value)
//     const dur = dayjs.duration(cur.diff(startWeek))
//     if (dayOrWeek.value == 2) {
    
//         // wait 原有组件设置完，再动作，防止被覆盖
//         nextTick(() => { document.getElementsByClassName('el-input__inner')[0].value = `第${dur.weeks()+1}周 (${cur.weekday(0).format('YY-MM-DD')} 至 ${cur.weekday(6).format('YY-MM-DD')})` })
//     } else {
//         nextTick(() => {
//             document.getElementsByClassName('el-input__inner')[0].value =
//                 `${cur.format('YYYY-MM-DD')} (第${dur.weeks() + 1 }周)`})
//     }
// }


function courseTbaleSpan({ row, column, rowIndex, columnIndex }) {
    // console.log(data)
    if (columnIndex >= 2)
        return [1, 1] //第一行
    // 第一行就往下查
    // 其余行先查看前一行是否相同，相同，返回0，0
    // 不同开始向下计算

    if (rowIndex != 0) {
        let beforeRow = courseTableData.value[rowIndex - 1]
        if (columnIndex == 0) { // 第1列
            if (beforeRow.content == row.content)
                return [0, 0]
        } else {// 第二列，必须和第一列同进退 
            // console.log(rowIndex, columnIndex, beforeRow.conent, row.content, beforeRow.labName, row.labName)
            if (beforeRow.content == row.content && beforeRow.labName == row.labName) {
                return [0, 0]
            }
        }
    }
    // 与前一行均不同， 从当前行往下查找，找到最后一个相同的index
    let rowspan = courseTableData.value.findLastIndex(v => {
        if (columnIndex === 0)
            return v.content === row.content
        // assert(columnIndex === 1)
        else
            return v.labName === row.labName && v.content === row.content
    }) - rowIndex + 1
    return [rowspan, 1]
}


watchEffect(
    () => {
        if (courses.value && sessionSelected.value && campusSelected.value) {
            tableDisplay.value = new Set() // 清空

            // let curData = courses.value
            // let content_list = sessionSelected.value.courseContents
            // console.log(content_list, curData)
            let tables = []
            sessionSelected.value.courseContents.forEach((content, index) => {
                // 检查这个节次的课程，继续 
                // console.log(curData)
                if (courses.value.hasOwnProperty(index)) {
                    // console.log(courses.value[index])

                    Object.keys(courses.value[index]).forEach((lab) => {
                        // console.log(lab)

                        // k是第几课
                        let dict = {}
                        // let keys = Object.keys(curData[content][lab])
                        if (dayOrWeek.value == 2) {
                            curWeeks.value.forEach(v => { // v 是日期
                                if (Object.keys(courses.value[index][lab]).includes(v)) {
                                    // 把 curData的下层再flat，也就是说每一行都是一个具体的课程,
                                    // 也可能是一个数组
                                    dict[v] = courses.value[index][lab][v]
                                    tableDisplay.value.add(v)
                                }
                            })
                            // 如果 在本周中有数据 ，即若进入上面分支，则补全其他信息
                            if (Object.keys(dict).length !== 0 ) {
                                dict['content'] = content
                                dict['labName'] = lab
                                tables.push(dict)
                            }
                        } else {// 按照天处理table
                            let curday = dayjs(dayViewSelected.value).format('YYYY-MM-DD')
                            // console.log(curData[content][lab])
                            if (Object.keys(courses.value[index][lab]).indexOf(curday) !== -1) {
                                // 存在
                                courses.value[index][lab][curday].forEach(kkk => {
                                    dict['data'] =kkk
                                    dict['content'] = content
                                    dict['labName'] = lab
                                    
                                    tables.push(dict)
                                }
                                )

                            } else {
                                // 不存在的情况,删掉多余的
                                // dict['remark'] = ''
                                // dict['student'] = ''
                                // dict['location'] = ''
                                // dict['user'] = ''
                                // dict['content'] = content
                                // dict['labName'] = lab
                                // tables.push(dict)
                            }

                        }
                    }
                    )

                }
            })
            courseTableData.value = tables
            return

        } else {
            courseTableData.value = []
            return
        }
    }

)
function dayAndWeekChange(dw) {
// 日、周切换 都切换到本周
    dayViewSelected.value = new Date()
    // if (dw === 2) // 从日视图切换到周，周选择实始化为空
    // {// 蹩脚的东西，凑合用吧
    //     // inpurtPrint()
    // } else if (dw === 1) {
        
    // }

}
// 取课程数据 
watchEffect(async () => {
    if (sessionSelected.value && campusSelected.value) {
        loading.value = true
        if (campusSelected.value.trim().length === 0) {
            // 无校区时，不用调用后端
            loading.value = false
        } else {
            await courseApi.getAllCourseHome(sessionSelected.value.sessionId, campusSelected.value).then(res => {
                courses.value = res.data
            })
            loading.value = false
        }
    }

})

watchEffect( () => {

    labsApi.getLabByCampus().then(res => {
        labs.value = res.data
        //  campus.value = labs.value
        campus.value = Object.keys(labs.value)
        campusSelected.value = campus.value.length === 0 ? '' : campus.value[0]

    });
})
watchEffect( () => {
     sessionApi.getSessionsInfos().then(res => {
       sessions.value = res.data
      
       //    sessionSelected.value = null
       if (sessions.value.length != 0) {
           let findRet = sessions.value.find(v => v.cur === true)
           if (typeof findRet != 'undefined') {
               sessionSelected.value = findRet
               return
           }
       }
       
   });
    


})

onUpdated(() => {
    const startWeek = new dayjs(sessionSelected.value.startTime)
    const cur = new dayjs(dayViewSelected.value)
    const dur = dayjs.duration(cur.diff(startWeek))
    if (dayOrWeek.value == 2) {

        // wait 原有组件设置完，再动作，防止被覆盖
        nextTick(() => { document.getElementsByClassName('el-input__inner')[0].value = `第${dur.weeks() + 1}周 (${cur.weekday(0).format('YY-MM-DD')} 至 ${cur.weekday(6).format('YY-MM-DD')})` })
    } else {
        nextTick(() => {
            document.getElementsByClassName('el-input__inner')[0].value =
                `${cur.format('YYYY-MM-DD')} (第${dur.weeks() + 1}周)`
        })
    }
})

const msg = [
    {
        content: '有课',
        timestamp: '2018-04-12 20:46',
        size: 'large',
        type: 'primary',
        icon: MoreFilled,
    },
    {
        content: '有假',
        timestamp: '2018-04-03 20:46',
        color: '#0bbd87',
    },
    {
        content: '值班',
        timestamp: '2018-04-03 20:46',
        size: 'large',
    },
    {
        content: '维护',
        timestamp: '2018-04-03 20:46',
        type: 'primary',
        hollow: true,
    },
    {
        content: '考试',
        timestamp: '2018-04-03 20:46',
    },
]

</script>

<style lang="less" scoped>
.outer {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    gap: 10px;
    width: 100%;
    height: 100%;
    margin-top: 20px;
    margin-left: 20px;

    .left {

        display: flex;
        flex-direction: column;
        width: 85%;
        vertical-align: middle;
        justify-content: space-between;

        .headerSelect {
            height: 80px;
            width: 100%;

            // scope 中生效 s
            ::v-deep .el-date-editor {
                width: 280px;
                flex: 1;
                min-width: 30%;
            }
        }


        .mainbox {
            width: 100%;
            flex-grow: 3;

            .capmus-radio {
                border: 1px solid #dcdfe6;
                border-radius: 1px;
                padding-right: 20px;
                padding-top: 0px;
                padding-bottom: 0px;
                padding-left: 20px;
            }

            ::v-deep .coure_table {
                .el-table--empty-block {
                    width: 1px;
                }

                .el_table .cell {
                    padding: 1px, 0px
                }


                .el-table td,
                .el-table th {
                    text-align: center;
                    height: 15px;
                    padding: 0px 0px;
                    width: 15px;
                }
            }
        }
    }

    .msg {
        width: 15%;
        height: 100%;
        padding: 10px, 15px;
        margin-top: 30px;
        margin-right: 20px;
    }
}
</style>
